package com.py.net.coder;

import java.lang.reflect.Method;
import java.util.List;

import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.GeneratedMessageV3.Builder;
import com.google.protobuf.MessageLite;
//import com.py.net.proto.ProtoMapper;
import com.py.chat.proto.ProtoMapper;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class ProtoByteDecoder extends ByteToMessageDecoder {

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		// TODO byteBuf解码成 byte[]
		if (in.readableBytes() < 8) {
			return;
		}
		in.markReaderIndex();
		int type = in.readInt();//协议类型
//		int readerIndex = in.readerIndex();
		int dateLength = in.readInt();//数据长度
		if (in.readableBytes() < dateLength) {
			in.resetReaderIndex();
//			in.readerIndex(readerIndex);
			return;
		}
		byte[] data = new byte[dateLength];
		in.readBytes(data);
		Method newBuilder = ProtoMapper.getMessageClass(type).getMethod("newBuilder");
		GeneratedMessageV3.Builder builder = (Builder) newBuilder.invoke(null);
		MessageLite msg = builder.mergeFrom(data).build();
		out.add(msg);
		return ;
	}

}
